package com.jz.netthings.netty.server;

import com.jz.netthings.netty.protocol.BasePacket;
import com.jz.netthings.netty.protocol.bean.ZxdcLoginPacket;
import com.jz.netthings.netty.protocol.bean.ZxdcMsgPacket;
import com.jz.netthings.netty.support.Attributes;
import com.jz.netthings.netty.support.ServerHandlerSupport;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Service("nettyLogServerHandler")
@ChannelHandler.Sharable
public class NettyLogServerHandler extends SimpleChannelInboundHandler {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${jz.zxdc.dbPath}")
    private String dbPath;
    @Autowired
    ServerHandlerSupport nettyServerHandlerSupport;

    Map<ChannelHandlerContext,String> map = new HashMap<>();

    /**
     * 存储数据库文件名的Map
     */
    private static HashMap<ChannelHandlerContext,String> ctxLogMap 	=  new HashMap<ChannelHandlerContext,String>();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj) throws Exception {

        if (obj instanceof String) {
            //文件名
            String fileName = (String)obj;
            int index = fileName.lastIndexOf("/");
            fileName = fileName.substring(index + 1);
            ctxLogMap.put(ctx,fileName);

            ByteBuf buf = Unpooled.buffer();
            buf.writeInt(252);
            ctx.writeAndFlush(buf);

        } else if (obj instanceof byte[]) {
            //文件内容
            byte[] bytes = (byte[]) obj;

            String oldFileName = ctxLogMap.get(ctx);
            String newFileName = oldFileName.replaceAll("-","");
            int indexOf = newFileName.indexOf(".rd") - 2;
            newFileName = newFileName.replaceAll("_","") .substring(0,indexOf);

            String[] strs = AdscmDateUtils.getYearMonthDay(new Date());
            newFileName = dbPath + strs[0] + "\\"+strs[1]+"\\"+strs[2]+"\\db" + newFileName;

//            AdscmBaseUtils.getInstance().writeFileToDisk(bytes,dbPath + ctxLogMap.get(ctx));
            AdscmBaseUtils.getInstance().writeFileToDisk(bytes,newFileName);

            ByteBuf buf = Unpooled.buffer();
            buf.writeInt(0);
            ctx.writeAndFlush(buf);

            buf = Unpooled.buffer();
            buf.writeInt(252);
            ctx.writeAndFlush(buf);

            final String nf = newFileName;

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        nettyServerHandlerSupport.doAnalysisZxdcDB(oldFileName,nf);
                    }catch (Exception e){
                        logger.error("处理浆机上传的数据库文件异常",e);
                    }
                }
            }).start();


        }/*else if(obj instanceof Integer[]){
            System.out.println("000025225225225225225200000");
            System.out.println(obj);
            ByteBuf buf = Unpooled.buffer();
            buf.writeInt(252);
            ctx.writeAndFlush(buf);
        }*/
        else if(obj instanceof Integer){
            System.out.println("000025225225225225225200000");
            System.out.println(obj);
            ByteBuf buf = Unpooled.buffer();
            buf.writeInt(251);
            ctx.writeAndFlush(buf);
        }
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
                logger.info("服务器给单采机Log端【" + ctx.channel().remoteAddress() + "】发送心跳信息...");

                NettyMsgHelper.sendOnlineMsg(ctx);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接的客户端【nettyLogServerHandler】地址:" + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {

        super.channelRead(ctx,obj);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //捕捉异常信息
        logger.error(cause.getMessage() + "【" + ctx.channel().remoteAddress() + "】");
        nettyServerHandlerSupport.freeMachineData(ctx);
        //出现异常时关闭channel
        ctx.close();
        super.exceptionCaught(ctx,cause);
    }
}